/*
 * @lc app=leetcode.cn id=740 lang=javascript
 *
 * [740] 删除并获得点数
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number}
 */
var deleteAndEarn = function (nums) {
  const maxVal = Math.max(...nums);
  const cost = new Array(maxVal + 1).fill(0);
  for (const val of nums) {
    cost[val] += val;
  }
  // cost为拿到从0到maxVal的等值累计值数组
  return rob(cost);
};

/**
 * @param {number[]} cost
 * @return {number}
 */
function rob(cost) {
  if (cost.length <= 2) return Math.max(...cost);
  const curMax = [cost[0], Math.max(cost[0], cost[1])];
  for (let i = 2; i < cost.length; i++) {
    curMax[i] = Math.max(curMax[i - 2] + cost[i], curMax[i - 1]);
  }
  return curMax[cost.length - 1];
}
// @lc code=end
